package com.foreverwin.mes.lims.service.impl;

import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.base.FrontPage;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.foreverwin.mes.lims.mapper.BadEntryOfWorkshopMateMapper;
import com.foreverwin.mes.lims.model.BadEntryOfWorkshopMate;
import com.foreverwin.mes.lims.service.BadEntryOfWorkshopMateService;
import com.sap.me.extension.Services;
import com.sap.me.frame.domain.BusinessException;
import com.sap.me.frame.transitionutils.Exceptions;
import com.sap.me.inventory.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mark
 * @since 2020-03-08
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BadEntryOfWorkshopMateServiceImpl extends ServiceImpl<BadEntryOfWorkshopMateMapper, BadEntryOfWorkshopMate> implements BadEntryOfWorkshopMateService {


    @Autowired
    private BadEntryOfWorkshopMateMapper badEntryOfWorkshopMateMapper;

    @Override
    public Page<BadEntryOfWorkshopMate> selectPage(FrontPage<BadEntryOfWorkshopMate> frontPage, BadEntryOfWorkshopMate badEntryOfWorkshopMate) {
        EntityWrapper<BadEntryOfWorkshopMate> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(badEntryOfWorkshopMate);
        return super.selectPage(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<BadEntryOfWorkshopMate> selectList(BadEntryOfWorkshopMate badEntryOfWorkshopMate) {
        EntityWrapper<BadEntryOfWorkshopMate> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(badEntryOfWorkshopMate);
        return super.selectList(queryWrapper);
    }

    public List<BadEntryOfWorkshopMate> selectInventoryBatch(BadEntryOfWorkshopMate badEntryOfWorkshopMate) {
        String storeLocationBo = HandleEnum.STORAGE_LOCATION.getHandle(badEntryOfWorkshopMate.getSite(),badEntryOfWorkshopMate.getWarehouse());
        return badEntryOfWorkshopMateMapper.selectInventoryBatch(badEntryOfWorkshopMate.getSite(),storeLocationBo);
    }

    public List<BadEntryOfWorkshopMate> selectInventoryBatchAll(BadEntryOfWorkshopMate badEntryOfWorkshopMate) {
        return badEntryOfWorkshopMateMapper.selectInventoryBatchAll(badEntryOfWorkshopMate.getSite());
    }

    public boolean saveWithStockScrapping(BadEntryOfWorkshopMate badEntryOfWorkshopMate,Boolean isLocalTest) {
        String site = CommonMethods.getSite();
        insertOrUpdate(badEntryOfWorkshopMate);
        //-------------------------------------------------------------------------------------------------------------------
        try {
            InventoryStatusEnum status;
            String reasonCode;
            String comments;
            String determineResult = badEntryOfWorkshopMate.getDetermineResult();
            if( determineResult==null || "".equalsIgnoreCase(determineResult) ){
                status=InventoryStatusEnum.QUARANTINE;
                reasonCode="NC-INV";
                comments="库存不良判定-隔离";
            }else{
                if( determineResult.equalsIgnoreCase("报废") ){
                    status=InventoryStatusEnum.AVAILABLE;
                    reasonCode="SCR-SCRAP";
                    comments="库存不良判定-报废";
                }else{
                    status=InventoryStatusEnum.AVAILABLE;
                    reasonCode="RTN-RETURN_TO_INVENTORY";
                    comments="库存不良判定-让步接收";
                }
            }
            if(!isLocalTest) {
                stockScrapping(site, status, reasonCode, comments, badEntryOfWorkshopMate);
            }
        } catch (com.sap.me.frame.domain.BusinessException e) {
            throw com.foreverwin.mes.core.exception.BusinessException.build(Exceptions.convert(e).toString());
        }
        return true;
    }

    public static void stockScrapping( String site,InventoryStatusEnum status,String reasonCode,String comments,BadEntryOfWorkshopMate badEntryOfWorkshopMate) throws BusinessException {
        InventoryServiceInterface inventoryServiceInterface = Services.getService("com.sap.me.inventory", "InventoryService", site);
        Inventory inventory = inventoryServiceInterface.findInventory(new InventoryIdentifier(badEntryOfWorkshopMate.getInventoryBatch()));
        Long scrapQty = badEntryOfWorkshopMate.getScrapQty();
        if( scrapQty == null ){
            scrapQty = 0l;
        }
        if (inventory != null) {
            InventoryValidateAndUpdateRequest updateRequest = new InventoryValidateAndUpdateRequest();
            updateRequest.setInventoryId(inventory.getInventoryId());
            updateRequest.setItemRef(inventory.getItemRef());
            updateRequest.setQuantityOnHand(inventory.getQtyOnHand().subtract(BigDecimal.valueOf(scrapQty)));
            updateRequest.setStatus(status);
            updateRequest.setReasonCodeRef(HandleEnum.REASON_CODE.getHandle(site, reasonCode, "I"));
            updateRequest.setComments( comments );
            updateRequest.setAssyDataTypeRef(inventory.getAssyDataTypeRef());
            updateRequest.setOperationLocationRef(inventory.getOperationLocRef());
            updateRequest.setOperationLocationReserve(inventory.isOperationLocRes());
            updateRequest.setShopOrderLocationRef(inventory.getShopOrderLocRef());
            updateRequest.setShopOrderLocationReserve(inventory.isShopOrderLocRes());
            updateRequest.setWorkCenterLocationRef(inventory.getWorkCenterLocRef());
            updateRequest.setWorkCenterLocationReserve(inventory.isWorkCenterLocRes());
            updateRequest.setResourceLocationRef(inventory.getResourceLocRef());
            updateRequest.setResourceLocationReserve(inventory.isResourceLocRes());
            updateRequest.setStorageLocationRef(inventory.getStorageLocationRef());
            updateRequest.setModifiedDateTime(inventory.getModifiedDateTime());
            updateRequest.setAssemblyDataList(inventory.getAssemblyDataList());
            inventoryServiceInterface.validateAndUpdate(updateRequest);
        }
    }

    public BadEntryOfWorkshopMate selectByHandle( String handle ){
        return badEntryOfWorkshopMateMapper.selectByHandle( handle );
    }

}